/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dp1.titandevelop.titano.view.logist;

import dp1.titandevelop.titano.bean.Mensajes;
import dp1.titandevelop.titano.persistent.Cotizacion;
import dp1.titandevelop.titano.persistent.DetalleCotizacion;
import dp1.titandevelop.titano.persistent.Proveedor;
import dp1.titandevelop.titano.service.FacturaCompraService;
import dp1.titandevelop.titano.service.OrdenCompraService;
import dp1.titandevelop.titano.service.ProveedorService;
import java.awt.Dimension;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import javax.swing.JOptionPane;
import javax.swing.table.AbstractTableModel;

/**
 *
 * @author chrestean
 */
public class ModulosT_LOG_NuevaOrdCompra extends javax.swing.JInternalFrame {

    /**
     * Creates new form TitanoInternalSegADMUserNew
     */
    private ModulosT_LOG_AdministrarOrdenCompra caller = null;

    
    public ModulosT_LOG_NuevaOrdCompra(ModulosT_LOG_AdministrarOrdenCompra caller) {
        initComponents();
        this.caller = caller;
        this.tableCotizaciones.setModel(modeloCotizaciones);
        this.tableDetalleCotizaciones.setModel(modeloDetalleCotizaciones);
        this.txtMontoTotal.setText("0");
        this.datePkEntrega.setDate( new Date() );
        this.btElliminar.setEnabled(false);
    }
    private ArrayList<DetalleCotizacion> listaDetalleCotizacion = new ArrayList<DetalleCotizacion>();
    private ArrayList<Cotizacion> listaCotizaciones = new ArrayList<Cotizacion>();
    private AbstractTableModel modeloCotizaciones = new AbstractTableModel() {
        @Override
        public int getRowCount() {
            return listaCotizaciones.size();

        }

        @Override
        public int getColumnCount() {
            return 3;
        }

        @Override
        public Object getValueAt(int fi, int co) {
            switch (co) {
                case 0:
                    return listaCotizaciones.get(fi).getIdcotizacion();
                case 1:
                    return new SimpleDateFormat("dd-MM-yyyy").format(listaCotizaciones.get(fi).getFecharegistro());
           
                case 2:
                    return listaCotizaciones.get(fi).getToOrdenCompra().getIdordencompra() != 0 ? listaCotizaciones.get(fi).getToOrdenCompra().getIdordencompra() : "Ninguna";

            }
            return null;
        }

        @Override
        public String getColumnName(int col) {
            String[] titles = {"Id Cotización", "Fecha de Registro", "Orden de Compra"};
            return titles[col];
        }
    };
    private AbstractTableModel modeloDetalleCotizaciones = new AbstractTableModel() {
        @Override
        public int getRowCount() {
            return listaDetalleCotizacion.size();

        }

        @Override
        public int getColumnCount() {
            return 4;
        }

        @Override
        public Object getValueAt(int fi, int co) {
            switch (co) {
                case 0:
                    return listaDetalleCotizacion.get(fi).getToRequerimientoXProducto().getToProducto().getDescripcion();
                case 1:
                    return listaDetalleCotizacion.get(fi).getCantidad();
                case 2:
                    return listaDetalleCotizacion.get(fi).getToRequerimientoXProducto().getToProducto().getUm();
                case 3:
                    return listaDetalleCotizacion.get(fi).getPrecio();
            }
            return null;
        }

        // 
        @Override
        public String getColumnName(int col) {
            String[] titles = {"Producto", "Cantidad", "Unidades", "Precio"};
            return titles[col];
        }
    };

 

    public void agregarCotizacionALista(Cotizacion c) {
        listaCotizaciones.add(c);
        listaDetalleCotizacion.addAll(c.getDetalleCotizacionArray());

    }

    public void refrescarTabla() {
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        txtProveedor = new javax.swing.JTextField();
        datePkEntrega = new org.jdesktop.swingx.JXDatePicker();
        jLabel2 = new javax.swing.JLabel();
        jButton3 = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        btElliminar = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        tableCotizaciones = new javax.swing.JTable();
        btnGuardar = new javax.swing.JButton();
        btnSalir = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tableDetalleCotizaciones = new javax.swing.JTable();
        txtMontoTotal = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();

        setTitle("Nueva Orden de Compra");

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Datos De Distribuidor", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 11))); // NOI18N
        jPanel1.setFont(new java.awt.Font("Tekton Pro", 0, 11)); // NOI18N

        jLabel3.setText("Proveedor");

        txtProveedor.setEnabled(false);

        jLabel2.setText("Fecha Entrega :");

        jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/buscar2.png"))); // NOI18N
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/agregar.png"))); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        btElliminar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/eliminar.png"))); // NOI18N
        btElliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btElliminarActionPerformed(evt);
            }
        });

        tableCotizaciones.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        tableCotizaciones.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tableCotizacionesMouseClicked(evt);
            }
        });
        jScrollPane2.setViewportView(tableCotizaciones);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(15, 15, 15)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addGap(18, 18, 18)
                        .addComponent(txtProveedor, javax.swing.GroupLayout.PREFERRED_SIZE, 139, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButton3)
                        .addGap(36, 36, 36)
                        .addComponent(jLabel2)
                        .addGap(2, 2, 2)
                        .addComponent(datePkEntrega, javax.swing.GroupLayout.PREFERRED_SIZE, 139, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 516, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(btElliminar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                .addContainerGap(15, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel3)
                        .addComponent(txtProveedor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(datePkEntrega, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel2))
                    .addComponent(jButton3))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jButton1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btElliminar))
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(24, Short.MAX_VALUE))
        );

        btnGuardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/grabar.png"))); // NOI18N
        btnGuardar.setToolTipText("Guardar");
        btnGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGuardarActionPerformed(evt);
            }
        });

        btnSalir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/cancelar.png"))); // NOI18N
        btnSalir.setToolTipText("Salir");
        btnSalir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSalirActionPerformed(evt);
            }
        });

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Cotización de Productos", javax.swing.border.TitledBorder.LEFT, javax.swing.border.TitledBorder.DEFAULT_POSITION));

        tableDetalleCotizaciones.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "ID Producto", "Producto", "Cantidad", "Monto"
            }
        ));
        jScrollPane1.setViewportView(tableDetalleCotizaciones);

        txtMontoTotal.setEditable(false);
        txtMontoTotal.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtMontoTotalActionPerformed(evt);
            }
        });

        jLabel1.setText("Monto Total");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 601, Short.MAX_VALUE)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtMontoTotal, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 139, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtMontoTotal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addContainerGap(12, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(btnGuardar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnSalir))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGap(20, 20, 20)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                .addContainerGap(15, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(8, 8, 8)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(2, 2, 2)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnSalir)
                    .addComponent(btnGuardar))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void txtMontoTotalActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtMontoTotalActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtMontoTotalActionPerformed

    private void btnSalirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalirActionPerformed
        ModulosT_LOG_AdministrarOrdenCompra admCompras = new ModulosT_LOG_AdministrarOrdenCompra();
        this.getParent().add(admCompras);

        Dimension desktopSize = this.getParent().getSize();
        Dimension jInternalFrameSize = admCompras.getSize();
        admCompras.setLocation((desktopSize.width - jInternalFrameSize.width) / 2,
                (desktopSize.height - jInternalFrameSize.height) / 4);

        admCompras.show();
        this.dispose();
    }//GEN-LAST:event_btnSalirActionPerformed

    public Boolean agregarCotizacion(Cotizacion c) {
        for (int i = 0; i < this.listaCotizaciones.size(); i++) {
            if (this.listaCotizaciones.get(i).getIdcotizacion().equals(c.getIdcotizacion())) {
                return false;
            }
        }
        this.txtMontoTotal.setText("" + (Float.parseFloat(this.txtMontoTotal.getText()) + c.getPreciototal()));

        this.listaCotizaciones.add(c);
        this.modeloCotizaciones.fireTableDataChanged();
        if (this.listaCotizaciones.size() > 0) {
            this.txtProveedor.setEnabled(false);
        }

        this.listaDetalleCotizacion.addAll(c.getDetalleCotizacionArray());
        this.modeloDetalleCotizaciones.fireTableDataChanged();
        return true;
    }
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        if ( !this.txtProveedor.getText().equals("") ) {
            // TODO add your handling code here:
            ProveedorService ps = new ProveedorService();

            Proveedor p = ps.buscarPorId(null, Integer.parseInt(this.txtProveedor.getText()));
            SeleccionarCotizacionPorProveedor sc = new SeleccionarCotizacionPorProveedor(this,p);
            this.getParent().add(sc);
            sc.show();
            //this.hide();

            //this.txtProveedor.setEnabled(false);
        } else {
            JOptionPane.showMessageDialog(this, "Primero especifique un proveedor.", "Campo faltante", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void btElliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btElliminarActionPerformed
        // sacar cotizacion
        int idCot = this.listaCotizaciones.get(this.tableCotizaciones.getSelectedRow()).getIdcotizacion();
        this.txtMontoTotal.setText("" + (Float.parseFloat(this.txtMontoTotal.getText()) - this.listaCotizaciones.get(this.tableCotizaciones.getSelectedRow()).getPreciototal()));

        this.listaCotizaciones.remove(this.tableCotizaciones.getSelectedRow());
        this.modeloCotizaciones.fireTableDataChanged();
        if (this.listaCotizaciones.isEmpty()) {
            this.txtProveedor.setEnabled(true);
        }
        ArrayList<DetalleCotizacion> listaDCAux = new ArrayList<DetalleCotizacion>();

        for (int i = 0; i < this.listaDetalleCotizacion.size(); i++) {
            if (!this.listaDetalleCotizacion.get(i).getToCotizacion().getIdcotizacion().equals(idCot)) {
                listaDCAux.add(this.listaDetalleCotizacion.get(i));
            }
        }

        this.listaDetalleCotizacion = listaDCAux;
        this.modeloDetalleCotizaciones.fireTableDataChanged();
    }//GEN-LAST:event_btElliminarActionPerformed

    private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardarActionPerformed
        // guardar esto
        Mensajes m = new Mensajes();
        if ( !this.listaCotizaciones.isEmpty() ) {
            //FacturaCompraService fs = new FacturaCompraService();
            //fs.insertarFactura(this.listaCotizaciones, Float.parseFloat(this.txtMontoTotal.getText()));
            OrdenCompraService os = new OrdenCompraService();
            
            os.insertarOrdenCompra(this.listaCotizaciones, this.datePkEntrega.getDate(), new Date(), 1);
            JOptionPane.showInternalMessageDialog(this.getRootPane(), m.getRegistrado(),"Mensaje",JOptionPane.INFORMATION_MESSAGE);
            
        } else {
            JOptionPane.showInternalMessageDialog(this.getRootPane(), m.getCompletarCampos(), "Aviso", JOptionPane.WARNING_MESSAGE);
        }
        this.caller.show();
        this.dispose();
    }//GEN-LAST:event_btnGuardarActionPerformed

    public void setIdProv(int id) {
        this.txtProveedor.setText(""+id);
        
    }
    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        ModulosT_LOG_BuscarProveedor bp = new ModulosT_LOG_BuscarProveedor(this);
        this.getParent().add(bp);
        bp.show();
    }//GEN-LAST:event_jButton3ActionPerformed

    private void tableCotizacionesMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tableCotizacionesMouseClicked
        if(evt.getClickCount()==1){
            this.btElliminar.setEnabled(true);
        }
    }//GEN-LAST:event_tableCotizacionesMouseClicked

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btElliminar;
    private javax.swing.JButton btnGuardar;
    private javax.swing.JButton btnSalir;
    private org.jdesktop.swingx.JXDatePicker datePkEntrega;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable tableCotizaciones;
    private javax.swing.JTable tableDetalleCotizaciones;
    private javax.swing.JTextField txtMontoTotal;
    private javax.swing.JTextField txtProveedor;
    // End of variables declaration//GEN-END:variables
}
